package com.evendai.sipdemo.sip

import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import org.doubango.ngn.NgnNativeService
import org.doubango.ngn.events.NgnInviteEventArgs
import org.doubango.ngn.events.NgnMessagingEventArgs
import org.doubango.ngn.events.NgnMsrpEventArgs
import org.doubango.ngn.events.NgnRegistrationEventArgs
import org.doubango.utils.Util.sendBroadcastAsUser
import com.evendai.loglibrary.Timber

/**
 * 在Engine启动的时候会开启这个服务，在Engine关闭的时候会停止这个服务
 * 这个类在Engine的getNativeServiceClass方法中返回给框架调用
 */
class NativeService : NgnNativeService() {

    private val mSipEventProcessor = SipEventProcessor()

    private val mBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                NgnMessagingEventArgs.ACTION_MESSAGING_EVENT -> mSipEventProcessor.processMessageEvent(intent)
                NgnMsrpEventArgs.ACTION_MSRP_EVENT -> mSipEventProcessor.processMSRPEvent(intent)
                NgnInviteEventArgs.ACTION_INVITE_EVENT -> mSipEventProcessor.processInviteEvent(intent)
                NgnRegistrationEventArgs.ACTION_REGISTRATION_EVENT -> mSipEventProcessor.processRegisterEvent(intent)
            }
        }
    }

    override fun onCreate() {
        super.onCreate()
        Timber.i("onCreate")

        // 注册Sip事件广播接收者
        val intentFilter = IntentFilter().apply {
            addAction(NgnInviteEventArgs.ACTION_INVITE_EVENT)
            addAction(NgnMessagingEventArgs.ACTION_MESSAGING_EVENT)
            addAction(NgnMsrpEventArgs.ACTION_MSRP_EVENT)
            addAction(NgnRegistrationEventArgs.ACTION_REGISTRATION_EVENT)
        }
        registerReceiver(mBroadcastReceiver, intentFilter)

        // 发送Engine启动完毕广播
        sendBroadcastAsUser(Intent(ACTION_ENGINE_STARTED))
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        Timber.i("onStartCommand")
        return Service.START_NOT_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        Timber.i("onDestroy")
        unregisterReceiver(mBroadcastReceiver)
        mSipEventProcessor.onDestroy()
    }

    companion object {
        /** Action：Engine启动完成  */
        const val ACTION_ENGINE_STARTED = "NativeService.ACTION_ENGINE_STARTED"
    }
}